package com.example.module_word.activity

import android.graphics.BitmapFactory
import android.net.Uri
import android.util.Log
import android.util.Size
import android.view.Surface
import android.widget.Toast
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageCapture
import androidx.camera.core.ImageCaptureException
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.core.content.ContextCompat
import androidx.core.net.toUri
import com.bdy.translate.listener.AnotherResultListener
import com.bdy.translate.util.BdyPhotoTranslateTool
import com.bdy.translate.util.TranslateUtil
import com.blankj.utilcode.util.ImageUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.example.module_word.databinding.ActivityCameraHomeBinding
import com.example.module_word.`interface`.DialogListener
import com.fenghuajueli.lib_pictureselect.PhotoSelectorBuilder
import com.fenghuajueli.lib_pictureselect.config.PhotoConfig
import com.fenghuajueli.libbasecoreui.baseswitch.PublicFunction
import com.fenghuajueli.libbasecoreui.baseswitch.SwitchKeyUtils
import com.fenghuajueli.libbasecoreui.utils.MyStatusBarUtils
import com.fenghuajueli.libbasecoreui.viewmodel.BaseViewModel2
import com.fenghuajueli.libbasecoreui.viewmodel.BaseViewModelActivity2
import com.example.module_word.dialog.pictureTranslationDialog
import com.example.module_word.dialog.setDiaLogDissmiss
import com.ll.module_translate.entity.TransResult
import com.ll.module_translate.utils.Scanning
import java.io.File
import java.text.SimpleDateFormat
import java.util.Locale
import java.util.concurrent.Executors

class CameraActivity : BaseViewModelActivity2<BaseViewModel2, ActivityCameraHomeBinding>() {

    private val imageCapture: ImageCapture by lazy {
        ImageCapture.Builder()
            .setTargetRotation(Surface.ROTATION_0)//设置旋转角度,并且只能有4个旋转方向属性ROTATION_0/ROTATION_90/ROTATION_180/ROTATION_270
            .setIoExecutor(Executors.newSingleThreadExecutor())//设置执行IO线程
            .setCaptureMode(ImageCapture.CAPTURE_MODE_MINIMIZE_LATENCY) //设置低延迟
            .setTargetResolution(Size(720, 1280)) //设置分辨率
            .build()
    }

    private lateinit var translateTool: BdyPhotoTranslateTool

    private  var picUri: Uri? = null

    override fun createViewModel(): BaseViewModel2 {
        return BaseViewModel2()
    }

    override fun createViewBinding(): ActivityCameraHomeBinding {
        return ActivityCameraHomeBinding.inflate(layoutInflater)
    }

    override fun initView() {
        MyStatusBarUtils.setStatusBarWhite(this, "#ffffff")

        binding.ivBack.setOnClickListener {
            finish()
        }
        translateTool = BdyPhotoTranslateTool()
        translateTool.initbdyKey(TranslateUtil.defaultSecretKey, TranslateUtil.keyName)

        binding.tvYuan.text = Scanning.ScanFromToEnCn().first
        binding.tvMu.text = Scanning.ScanFromToEnCn().second

        startCamera()

        binding.ivSelectPic.setOnClickListener {
            if (!PublicFunction.checkCanUsedByPosition(1, true)) {
                return@setOnClickListener
            }
            PhotoSelectorBuilder.builder(this)
                .mode(PhotoConfig.Mode.PHOTO)
                .maxCount(1)
                .minCount(1)
                .listener {
                    picUri = it[0].uri.toUri()
                    transPic(it[0].path)
                }
        }

        binding.ivTakePhone.setOnClickListener {
            if (!PublicFunction.checkCanUsedByPosition(1, true)) {
                return@setOnClickListener
            }
            takePhoto()
        }

        binding.llFanYiYu.setOnClickListener {
            pictureTranslationDialog(this, true)
        }

        binding.tvYuan.setOnClickListener {
            pictureTranslationDialog(this, true)
        }

        binding.tvMu.setOnClickListener {
            pictureTranslationDialog(this, false)
        }

        setDiaLogDissmiss(object : DialogListener {
            override fun dismissDialog() {
                binding.tvYuan.text = Scanning.ScanFromToEnCn().first
                binding.tvMu.text = Scanning.ScanFromToEnCn().second
            }
        })
    }

    private fun startCamera() {
        val cameraProviderFuture = ProcessCameraProvider.getInstance(this)

        cameraProviderFuture.addListener({
            // 用于将相机的生命周期绑定到生命周期所有者
            val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get()

            // 创建预览
            val preview = Preview.Builder()
                .build()
                .also {
                    it.setSurfaceProvider(binding.surfaceView.surfaceProvider)
                }


            // 默认选择后置摄像头
            val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA

            try {
                // 在重新绑定之前取消绑定用例
                cameraProvider.unbindAll()

                // 将用例绑定到相机
                cameraProvider.bindToLifecycle(
                    this, cameraSelector, preview, imageCapture
                )

            } catch (exc: Exception) {
                Log.e("TAG", "Use case binding failed", exc)
            }

        }, ContextCompat.getMainExecutor(this))

    }


    private fun takePhoto() {
        showLoadingDialog("加载中...")
        // Get a stable reference of the modifiable image capture use case
        val imageCapture = imageCapture ?: return

        // Create time-stamped output file to hold the image
        val photoFile = File(
            filesDir,
            SimpleDateFormat(
                "yyyy-MM-dd-HH-mm-ss", Locale.CHINA
            ).format(System.currentTimeMillis()) + ".jpg"
        )

        // Create output options object which contains file + metadata
        val outputOptions = ImageCapture.OutputFileOptions.Builder(photoFile).build()

        // Set up image capture listener, which is triggered after photo has
        // been taken
        imageCapture.takePicture(
            outputOptions,
            ContextCompat.getMainExecutor(this),
            object : ImageCapture.OnImageSavedCallback {
                override fun onError(exc: ImageCaptureException) {
                    Log.e("TAG", "Photo capture failed: ${exc.message}", exc)
                }

                override fun onImageSaved(output: ImageCapture.OutputFileResults) {
                    output.savedUri?.let { uri -> picUri = uri }
                    val savedUri = Uri.fromFile(photoFile)
                    val msg = "Photo capture succeeded: $savedUri"
//                    Toast.makeText(baseContext, msg, Toast.LENGTH_SHORT).show()
                    Log.d("TAG", msg)
//                saveImageToGallery(this@CameraActivity, photoFile.absolutePath)
                    var bitmap = BitmapFactory.decodeFile(photoFile.absolutePath)
//                bitmap = ImageUtils.compressByScale(bitmap, 300, 1000)
//                ImageUtils.save2Album(bitmap, photoFile.absolutePath, Bitmap.CompressFormat.JPEG)
//                    TranslatePictureActivity.start(this@CameraActivity, photoFile.absolutePath)
                    transPic(photoFile.absolutePath)
                    LogUtils.d(ImageUtils.getSize(photoFile.absolutePath))
                }
            })
    }


    private fun transPic(file: String) {


        if (TranslateUtil.isReachingLimit()) {
            if (SwitchKeyUtils.getPayStatus()) {
                TranslateUtil.makeToast("因会员每日翻译字符数合计限制为1万字符，待明天再来翻译吧~", Toast.LENGTH_LONG)
            } else {
                TranslateUtil.makeToast("每日翻译字符数合计限制为3千字符，购买会员可解锁更多文字翻译", Toast.LENGTH_LONG)
            }
        }
        val from = Scanning.ScanFromToEn().first
        val to = Scanning.ScanFromToEn().second
        translateTool.transLateToOtherLanguage(from, to, File(file), object :
            AnotherResultListener {
            override fun Success(src: String?, res: String?) {
                hideLoadingDialog()
                val sumSrc = src!!.split("\n")
                val sumDst = res!!.split("\n")
                val results = mutableListOf<TransResult>()
                for (i in sumSrc.indices) {
                    results.add(TransResult(src = sumSrc[i], dst = sumDst[i]))
                }
                /* binding.root.post {
                     adapter.list = results
                     adapter.notifyItemRangeInserted(0, results.size)
                 }*/
                TranslateUtil.saveWordCount(src.length)

                TranslatePictureActivity.start(this@CameraActivity, results,picUri,binding.tvYuan.text,binding.tvMu.text)

            }

            override fun Failed(s: String?) {
                hideLoadingDialog()
                ToastUtils.showLong(s)
            }

        })

    }

}